package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.controller.handler.admin.UserListParams;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.enumeration.AuthStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.enumeration.WealthType;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Joe on 2018/1/23.
 */
public class UserListForManagerHandler extends SessionHandler<UserListParams> {
    @Override
    public String handle(UserListParams params, HttpServletRequest request) throws Exception {
        String hql = "from User where 1=1 ";
        List<Object> objects = new ArrayList<>();

        if (null != params.getRole()) {
            hql += "and role like '%\"" + params.getRole().name() + "\":true%' ";
            //objects.add("%\"" + params.getRole().name() + "\":true%");
        }

        if (!StringUtils.isEmpty(params.getKeyword())) {
            try {
                long userId = Long.parseLong(params.getKeyword());
                hql += "and (id=? or info like ?) ";
                objects.add(userId);
                objects.add("%" + params.getKeyword() + "%");
            } catch (NumberFormatException e) {
                hql += "and info like ? ";
                objects.add("%" + params.getKeyword() + "%");
            }
        }

        switch (params.getAuth()) {
            case 0:
                break;
            case 1:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.failed);
                break;
            case 2:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.checking);
                break;
            case 3:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.success);
                break;
            default:
                break;
        }

        switch (params.getSpecial()) {
            case 0:
                break;
            case 1:
                hql += "and special is true ";
                break;
            case 2:
                hql += "and special is false ";
                break;
        }

        UserStored loginUser = globalService.getUser(params.getUserId());
        if (!loginUser.getRole().isAdmin()) {
            if (params.getInviteUserId() > 0) {
                hql += "and inviteUserId = ? ";
                objects.add(params.getInviteUserId());
            } else {
                hql += "and inviteUserId = ? or teamUserId = ? ";
                objects.add(params.getUserId());
                objects.add(params.getUserId());
            }
        } else if (params.getInviteUserId() > 0) {
            hql += "and inviteUserId = ? ";
            objects.add(params.getInviteUserId());
        }

        BigDecimal countOfByHql = userDao.getCountOfByHql(hql, objects);
        hql += "order by id desc ";
        List<User> users = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());
        List<UserModel> userModels = new ArrayList<>();
        HashMap<Long, UserStored> userStoredHashMap = new HashMap<>();
        for (User user : users) {
            UserModel userModel = new UserModel(user, 2, globalVariablesService.getGlobalRule().getDefaultAvatar());
            userModel.setMoney(globalService.getUserWealthOfMoney(user.getId(), WealthType.money));
            userModel.setTotalProject(0);//todo:读取项目数量
            userModels.add(userModel);
            if (user.getInviteUserId() > 0 && !userStoredHashMap.containsKey(user.getInviteUserId())) {
                userStoredHashMap.put(user.getInviteUserId(), globalService.getUser(user.getInviteUserId()));
            }
        }
        return successMessage(userModels,
                new KeyValue("start", params.getStart()),
                new KeyValue("total", countOfByHql.intValue()),
                new KeyValue("users", userStoredHashMap)
        );
    }

    @Override
    public String result() throws Exception {
        return successMessage("用户列表");
    }

    @Override
    public ArrayList<Role> allowRoles() {
        return Role.all();
    }

    @Override
    public boolean needLog() {
        return false;
    }
}
